<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>canvas-dog</title>
	</head>
	<body>
		<canvas id="dog-walking" style="position: fixed;left: 0;bottom: 0;"></canvas>
		<script type="text/javascript">
			let canvas = document.getElementById("dog-walking");
			let dogAnimation = new DogAnimation(canvas);
			dogAnimation.start();
			
			//用类的方式组织代码
			class DogAnimation {
				constructor(canvas) {
					canvas.width = window.innerWidth;
					canvas.height = 200;
					this.canvas = canvas;
					this.ctx = this.canva.getContext('2d');
					//记录上一帧的时间
					this.lastWalkingTime = Date.now();
					//记录当前画的图片索引
					this.keyFrameIndex = -1;
					//存放加载后狗的图片
					this.dogPictures = [];
					//图片目录
					this.RES_PATH = 'img/dog';
					this.IMG_COUNT = 8;
					this.start();
				}
				async start() {
					//等待资源加载完成
					await this.loadResources();
//					this.walk();
					window.requestAnimationFrame(this.walk.bind(this));
				}
				loadResources() {
					let imagesPath = [];
					//准备图片src
					for(let i=0;i<this.IMG_COUNT;i++) {
						imagesPath.push(`${this.RES_PATH}/(${i})`);
						console.log(`${this.RES_PATH}/(${i})`);
					}
					let works = [];
					imagesPath.forEach(imgPath => {
						works.push(new Promise(resolve => {
							let img = new Image();
							img.onload = () => resolve(img);
							img.src = imgPath;
						}));
					});
					return new Promise(resolve => {
						//借助Promise.all知道所有图片已经加载好了
						Promise.all(work).then(dogPictures => {
							this.dogPictures = dogPictures;
							resolve();
						})
					})
				}
				walk() {
					//绘制狗的图片,每100ms一张
					let now = Date.now();
					if(now - this.lastWalkingTime > 100){
						//先清掉上一帧的内容
						this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
						//获取下一张图片的索引
						let keyFrameIndex = ++
					}
					//继续给下一帧注册一个函数
					window.requestAnimationFrame(this.walk.bind(this));
				}
			}
			
		</script>
	</body>
</html>
